import TIM from "../node_modules/tim-wx-sdk"
import TIMUploadPlugin from '../node_modules/tim-upload-plugin';
import COS from '../static/cos-wx-sdk-v5';
import $user from "./user.js";
import $config from "./config.js";
import $http from "./request.js";

let options = {
  SDKAppID: 1400761371 // 接入时需要将0替换为您的即时通信 IM 应用的 SDKAppID
};

function get_message_time(nowtime, mtime){
	if(mtime.toString().length == 10){
		mtime = mtime * 1000
	}
	var date = new Date(mtime);
	var Y = date.getFullYear() + '-';
	var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
	var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
	var h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':';
	var m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()) + '';
	var s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
	
	if (date.getFullYear()==nowtime.getFullYear() && date.getMonth==nowtime.getMonth && date.getDate() == nowtime.getDate()) {
		return h+m;
	} else{
		return M+D+h+m;
	}
}

export default {
	Tim: null,
	conversations:[],
	getTim(){
		if(!this.Tim){
			this.Tim = TIM.create(options);
			this.Tim.setLogLevel(1);
		}
		return this.Tim;
	},
	
	timLogin(){
		let tim = this.getTim();
		let __this = this;
		
		if(!$user.userinfo){
			return;
		}
		// 开始登录
		tim.login({userID: $user.userinfo.id, userSig: $user.userinfo.user_sig}).then(function(e){});
	},
	
	init(){
		let tim = this.getTim();
		let __this = this;
		
		// 监听事件，例如：
		tim.on(TIM.EVENT.SDK_READY, function(event) {
		// 收到离线消息和会话列表同步完毕通知，接入侧可以调用 sendMessage 等需要鉴权的接口
			__this.getConversationList();
			__this.getUnreadNum();
		});
		// 收到推送的单聊、群聊、群提示、群系统通知的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
		tim.on(TIM.EVENT.MESSAGE_RECEIVED, function(event){
			uni.$emit('messageUpdate', event.data)
			__this.getConversationList();
			__this.getUnreadNum();
			console.log("震动");
			plus.device.vibrate(400);

			// uni.vibrateLong({
			// 	success: function () {
			// 		console.log('success');
			// 	},
			// 	fail: function () {
			// 		console.log('fail');
			// 	}
			// });
		});
		// tim.on(TIM.EVENT.MESSAGE_RECEIVED, function(event) {
		// // 收到消息被撤回的通知
		// });
		tim.on(TIM.EVENT.MESSAGE_REVOKED, function(event) {
		// 收到消息被撤回的通知
		});
		tim.on(TIM.EVENT.MESSAGE_READ_BY_PEER, function(event) {
		// SDK 收到对端已读消息的通知，即已读回执。使用前需要将 SDK 版本升级至 v2.7.0 或以上。仅支持单聊会话。
		});
		tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, function(event) {
		// 收到会话列表更新通知，可通过遍历 event.data 获取会话列表数据并渲染到页面
		});
		tim.on(TIM.EVENT.GROUP_LIST_UPDATED, function(event) {
		// 收到群组列表更新通知，可通过遍历 event.data 获取群组列表数据并渲染到页面
		});
		tim.on(TIM.EVENT.PROFILE_UPDATED, function(event) {
		// 收到自己或好友的资料变更通知
		});
		tim.on(TIM.EVENT.BLACKLIST_UPDATED, function(event) {
		// 收到黑名单列表更新通知
		});
		tim.on(TIM.EVENT.ERROR, function(event) {
		// 收到 SDK 发生错误通知，可以获取错误码和错误信息
		});
		tim.on(TIM.EVENT.SDK_NOT_READY, function(event) {
		// 收到 SDK 进入 not ready 状态通知，此时 SDK 无法正常工作
		});
		tim.on(TIM.EVENT.KICKED_OUT, function(event) {
		// 收到被踢下线通知
		});
		tim.on(TIM.EVENT.NET_STATE_CHANGE, function(event) { 
		//  网络状态发生改变（v2.5.0 起支持）。 
		});
		
		//tim.registerPlugin({'tim-upload-plugin': TIMUploadPlugin});
		tim.registerPlugin({'cos-wx-sdk': COS});
	},
	
	getConversationList(){
		let tim = this.getTim();
		let __this = this;
		let nowtime = new Date();
		
		tim.getConversationList().then(function(e){
			//群置顶
			__this.conversations = []
			for(let i = 0; i < e.data.conversationList.length; i++){
				e.data.conversationList[i].lastMessage.lastTimeFormat = get_message_time(nowtime, e.data.conversationList[i].lastMessage.lastTime);
				if(e.data.conversationList[i].type == "GROUP"){
					__this.conversations.unshift(e.data.conversationList[i])
				}else{
					__this.conversations.push(e.data.conversationList[i])
				}
			}
			uni.$emit('conversationUpdate', {})
		});
	},
	
	getUnreadNum(){
		let tim = this.getTim();
		let __this = this;
		let unreadNum = 0;
		
		tim.getConversationList().then(function(e){
			for(let i = 0; i < e.data.conversationList.length; i++){
				unreadNum += e.data.conversationList[i].unreadCount;
			}
			
			plus.runtime.setBadgeNumber(unreadNum);
			
			if(unreadNum != 0){
				uni.setTabBarBadge({
				  index: 2,
				  text: unreadNum.toString()
				});
			}else{
				uni.removeTabBarBadge({
					index: 2,
				})
			}
		});
	},
	
	getGroupMemberList(groupID, page){
		let tim = this.getTim();
		let __this = this;
		let count = 50;
		let offset = (page - 1) * count
		
		return tim.getGroupMemberList({groupID: groupID, count: count, offset: offset});
	},
	
	getMessageList(conversationID, nextReqMessageID){
		let tim = this.getTim();
		let __this = this;
		let count = 15;
		
		let param;
		if(nextReqMessageID == null){
			param = {conversationID: conversationID, count: count};
		}else{
			param = {conversationID: conversationID, nextReqMessageID, count: count}
		}
		
		return tim.getMessageList(param);
	},
	
	setMessageRead(conversationID){
		let tim = this.getTim();
		let __this = this;
		
		tim.setMessageRead({conversationID: conversationID}).then(function(e){
			__this.getUnreadNum();
		});
	},
	
	async sendTIMMessage(message, toUid, conversationType){
		let tim = this.getTim();
		let __this = this;
		
		//校验是否有发送消息的权限
		if(conversationType == "C2C"){
			let [err,res] = await $http.post('user/validateMessage',{
				to_uid: toUid
			});
			if(!$http.errorCheck(err,res)){
				if(res.data.errno == 10000){
					setTimeout(function() {
						uni.navigateTo({
							url:'/pages/vip/vip'
						})
					}, 1000);
				}
				return;
			}
		}
		
		
		// 2. 发送消息
		let promise = tim.sendMessage(message);
		promise.then(function(imResponse) {
		  // 发送成功
		  let arr = [];
		  arr.push(imResponse.data.message);
		  uni.$emit('messageUpdate', arr);
		  __this.getConversationList();
		}).catch(function(imError) {
		  // 发送失败
		  console.warn('sendMessage error:', imError);
		  if(imError.code == "10017"){
			  uni.showToast({ title: '你已被禁言24小时!', icon:"none" });
		  }
		});
	},
	
	sendTextMessage(messageText, toUserId, conversationType){		
		let tim = this.getTim();
		
		let param = {
		  to: toUserId,
		  payload: {
		    text: messageText
		  },
		}
		if(conversationType == "C2C"){
			param.conversationType = TIM.TYPES.CONV_C2C
		}else{
			param.conversationType = TIM.TYPES.CONV_GROUP
		}
		
		let message = tim.createTextMessage(param);
		this.sendTIMMessage(message, toUserId, conversationType);
		
		if(conversationType == "C2C"){
			$http.post("Message/push", {uid: toUserId, text: messageText});
		}
	},
	
	sendImageMessage(imagePath, toUserId, conversationType){
		let tim = this.getTim();
		
		let param = {
		  to: toUserId,
		  payload: {
		    file: imagePath,
		  },
		  onProgress: function(event) {
		  			  uni.$emit('messageProgress', event);
		  			}
		}
		if(conversationType == "C2C"){
			param.conversationType = TIM.TYPES.CONV_C2C
		}else{
			param.conversationType = TIM.TYPES.CONV_GROUP
		}
		
		let message = tim.createImageMessage(param);
		
		this.sendTIMMessage(message, toUserId, conversationType);
		
		if(conversationType == "C2C"){
			$http.post("Message/push", {uid: toUserId, text:"[图片]"});
		}
	},
	
	sendVideoMessage(videoPath, toUserId, conversationType){
		let tim = this.getTim();
		
		let param = {
		  to: toUserId,
		  payload: {
		    file: videoPath,
		  },
		  onProgress: function(event) {
		  			  uni.$emit('messageProgress', event);
		  			}
		}
		if(conversationType == "C2C"){
			param.conversationType = TIM.TYPES.CONV_C2C
		}else{
			param.conversationType = TIM.TYPES.CONV_GROUP
		}
		
		let message = tim.createVideoMessage(param);
		
		this.sendTIMMessage(message, toUserId, conversationType);
		
		if(conversationType == "C2C"){
			$http.post("Message/push", {uid: toUserId, text:"[视频]"});
		}
	},
	
	sendAudioMessage(file, toUserId, conversationType){
		let tim = this.getTim();
		
		let param = {
		  to: toUserId,
		  payload: {
		    file: file,
		  },
		  onProgress: function(event) {
		  			  uni.$emit('messageProgress', event);
		  			}
		}
		if(conversationType == "C2C"){
			param.conversationType = TIM.TYPES.CONV_C2C
		}else{
			param.conversationType = TIM.TYPES.CONV_GROUP
		}
		
		let message = tim.createAudioMessage(param);
		
		this.sendTIMMessage(message, toUserId, conversationType);
		
		if(conversationType == "C2C"){
			$http.post("Message/push", {uid: toUserId, text:"[语音]"});
		}
	},
	
	deleteConversations(conversationID){
		let tim = this.getTim();
		let __this = this;
		
		let promise = tim.deleteConversation(conversationID);
		promise.then(function(imResponse) {
		  // 删除会话成功
		  console.log("deleteConversation succ")
		  __this.getConversationList()
		}).catch(function(imError) {
		  console.warn('deleteConversation error:', imError); // 删除会话失败的相关信息
		});
	},
	
	logout(){
		let tim = this.getTim();
		
		tim.off(TIM.EVENT.SDK_READY, function(event) {
		});
		tim.off(TIM.EVENT.MESSAGE_RECEIVED, function(event){
		});
		tim.off(TIM.EVENT.MESSAGE_REVOKED, function(event) {
		});
		tim.off(TIM.EVENT.MESSAGE_READ_BY_PEER, function(event) {
		});
		tim.off(TIM.EVENT.CONVERSATION_LIST_UPDATED, function(event) {
		});
		tim.off(TIM.EVENT.GROUP_LIST_UPDATED, function(event) {
		});
		tim.off(TIM.EVENT.PROFILE_UPDATED, function(event) {
		});
		tim.off(TIM.EVENT.BLACKLIST_UPDATED, function(event) {
		});
		tim.off(TIM.EVENT.ERROR, function(event) {
		});
		tim.off(TIM.EVENT.SDK_NOT_READY, function(event) {
		});
		tim.off(TIM.EVENT.KICKED_OUT, function(event) {
		});
		tim.off(TIM.EVENT.NET_STATE_CHANGE, function(event) { 
		});
		tim.logout();
	},
}	